package api

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
)

const (
	baiduAPIKey    = "APV9aZzKc3Vl2f4BLdEhX6ss"
	baiduSecretKey = "SHpZzwroxkGfB6IJZo7jkBI1bzFkbSIn"
)

func getAccessToken() (string, error) {
	url := fmt.Sprintf("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s", baiduAPIKey, baiduSecretKey)
	resp, err := http.Get(url)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	log.Println("response:", resp)

	body, _ := ioutil.ReadAll(resp.Body)
	var result struct {
		AccessToken string `json:"access_token"`
	}
	json.Unmarshal(body, &result)
	return result.AccessToken, nil
}

func WenxinChat(query string) (string, error) {
	token, err := getAccessToken()
	if err != nil {
		return "", err
	}

	url := fmt.Sprintf("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant?access_token=%s", token)
	reqBody := map[string]interface{}{
		"messages": []map[string]string{
			{"role": "user", "content": query},
		},
	}

	log.Printf("url: %s", url)
	log.Printf("query: %s", query)

	jsonData, _ := json.Marshal(reqBody)
	resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonData))
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	body, _ := ioutil.ReadAll(resp.Body)
	var result struct {
		Result string `json:"result"`
	}

	json.Unmarshal(body, &result)

	fmt.Println("result:", result)
	return result.Result, nil
}
